package com.translator.ui;

import com.translator.config.AppConfig;
import com.translator.engine.TranslationEngineFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设置对话框
 * 提供用户配置翻译引擎API密钥和网络代理设置的界面
 */
public class SettingsDialog extends JDialog {

    private JTabbedPane tabbedPane;
    private JPanel apiKeysPanel;
    private JPanel proxyPanel;
    private JButton saveButton;
    private JButton cancelButton;
    
    private Map<String, JTextField> apiKeyFields;
    private JCheckBox enableProxyCheckBox;
    private JTextField proxyHostField;
    private JTextField proxyPortField;
    private JTextField proxyUsernameField;
    private JPasswordField proxyPasswordField;
    
    private boolean configChanged = false;
    
    /**
     * 创建设置对话框
     * 
     * @param parent 父窗口
     */
    public SettingsDialog(Frame parent) {
        super(parent, "设置", true);
        initComponents();
        setupLayout();
        setupListeners();
        loadSettings();
        
        setSize(650, 500);
        setLocationRelativeTo(parent);
        setResizable(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    
    private void initComponents() {
        tabbedPane = new JTabbedPane();
        apiKeysPanel = new JPanel(new GridBagLayout());
        proxyPanel = new JPanel(new GridBagLayout());
        
        saveButton = new JButton("保存");
        cancelButton = new JButton("取消");
        
        apiKeyFields = new HashMap<>();
        
        enableProxyCheckBox = new JCheckBox("启用代理");
        proxyHostField = new JTextField(20);
        proxyPortField = new JTextField(5);
        proxyUsernameField = new JTextField(15);
        proxyPasswordField = new JPasswordField(15);
    }
    
    private void setupLayout() {
        // 设置API密钥面板
        setupApiKeysPanel();
        
        // 设置代理面板
        setupProxyPanel();
        
        // 添加选项卡并设置其属性
        tabbedPane.addTab("API密钥", apiKeysPanel);
        tabbedPane.addTab("网络代理", proxyPanel);
        tabbedPane.setFont(tabbedPane.getFont().deriveFont(Font.BOLD, 12));
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
        
        // 设置按钮大小和外观
        saveButton.setPreferredSize(new Dimension(90, 30));
        cancelButton.setPreferredSize(new Dimension(90, 30));
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        // 设置主面板
        JPanel mainPanel = new JPanel(new BorderLayout(0, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        mainPanel.add(tabbedPane, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
    }
    
    private void setupApiKeysPanel() {
        // 创建内容面板，使用GridBagLayout
        JPanel contentPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 10, 8, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 添加说明标签
        JLabel infoLabel = new JLabel("请为需要API密钥的翻译引擎设置密钥：");
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        contentPanel.add(infoLabel, gbc);
        
        // 获取所有引擎名称
        List<String> engineNames = TranslationEngineFactory.getAvailableEngineNames();
        int row = 1;
        
        for (String engineName : engineNames) {
            // 添加引擎名称标签
            gbc.gridx = 0;
            gbc.gridy = row;
            gbc.gridwidth = 1;
            gbc.weightx = 0.2;
            JLabel engineLabel = new JLabel(engineName + ":");
            contentPanel.add(engineLabel, gbc);
            
            // 添加API密钥输入框
            JTextField apiKeyField = new JTextField(25);
            apiKeyField.setMinimumSize(new Dimension(250, 28));
            apiKeyField.setPreferredSize(new Dimension(350, 28));
            apiKeyFields.put(engineName, apiKeyField);
            
            gbc.gridx = 1;
            gbc.weightx = 0.8;
            contentPanel.add(apiKeyField, gbc);
            
            row++;
        }
        
        // 创建滚动面板并添加内容面板
        JScrollPane scrollPane = new JScrollPane(contentPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        
        // 设置API密钥面板使用BorderLayout，并将滚动面板添加到中央
        apiKeysPanel.setLayout(new BorderLayout());
        apiKeysPanel.add(scrollPane, BorderLayout.CENTER);
    }
    
    private void setupProxyPanel() {
        // 创建内容面板，使用GridBagLayout
        JPanel contentPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 10, 8, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 添加代理启用复选框
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        enableProxyCheckBox.setFont(enableProxyCheckBox.getFont().deriveFont(Font.BOLD));
        contentPanel.add(enableProxyCheckBox, gbc);
        
        // 添加说明标签
        JLabel infoLabel = new JLabel("请配置HTTP代理服务器设置：");
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(15, 10, 10, 10);
        contentPanel.add(infoLabel, gbc);
        gbc.insets = new Insets(8, 10, 8, 10);
        
        // 添加代理主机设置
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        gbc.weightx = 0.2;
        JLabel hostLabel = new JLabel("代理主机:");
        contentPanel.add(hostLabel, gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        proxyHostField.setPreferredSize(new Dimension(350, 28));
        contentPanel.add(proxyHostField, gbc);
        
        // 添加代理端口设置
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.weightx = 0.2;
        JLabel portLabel = new JLabel("代理端口:");
        contentPanel.add(portLabel, gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        proxyPortField.setPreferredSize(new Dimension(80, 28));
        JPanel portPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        portPanel.add(proxyPortField);
        contentPanel.add(portPanel, gbc);
        
        // 添加代理用户名设置
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.weightx = 0.2;
        JLabel usernameLabel = new JLabel("用户名:");
        contentPanel.add(usernameLabel, gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        proxyUsernameField.setPreferredSize(new Dimension(200, 28));
        contentPanel.add(proxyUsernameField, gbc);
        
        // 添加代理密码设置
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.weightx = 0.2;
        JLabel passwordLabel = new JLabel("密码:");
        contentPanel.add(passwordLabel, gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        proxyPasswordField.setPreferredSize(new Dimension(200, 28));
        contentPanel.add(proxyPasswordField, gbc);
        
        // 创建滚动面板并添加内容面板
        JScrollPane scrollPane = new JScrollPane(contentPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        
        // 设置代理面板使用BorderLayout，并将滚动面板添加到中央
        proxyPanel.setLayout(new BorderLayout());
        proxyPanel.add(scrollPane, BorderLayout.CENTER);
    }
    
    private void setupListeners() {
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveSettings();
                configChanged = true;
                dispose();
            }
        });
        
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        
        enableProxyCheckBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean enabled = enableProxyCheckBox.isSelected();
                proxyHostField.setEnabled(enabled);
                proxyPortField.setEnabled(enabled);
                proxyUsernameField.setEnabled(enabled);
                proxyPasswordField.setEnabled(enabled);
            }
        });
    }
    
    private void loadSettings() {
        AppConfig config = AppConfig.getInstance();
        // 加载API密钥
        for (Map.Entry<String, JTextField> entry : apiKeyFields.entrySet()) {
            String engineName = entry.getKey();
            String apiKey = config.getApiKey(engineName);
            JTextField field = entry.getValue();
            field.setText(apiKey);
            field.setEditable(true);
            field.setEnabled(true);
        }
        // 加载代理设置
        enableProxyCheckBox.setSelected(config.isProxyEnabled());
        proxyHostField.setText(config.getProxyHost().isEmpty() ? "127.0.0.1" : config.getProxyHost());
        proxyPortField.setText(config.getProxyPort() == 0 ? "7890" : String.valueOf(config.getProxyPort()));
        proxyUsernameField.setText(config.getProxyUsername());
        proxyPasswordField.setText(config.getProxyPassword());
        boolean enabled = enableProxyCheckBox.isSelected();
        proxyHostField.setEnabled(enabled);
        proxyPortField.setEnabled(enabled);
        proxyUsernameField.setEnabled(enabled);
        proxyPasswordField.setEnabled(enabled);
    }
    
    private void saveSettings() {
        AppConfig config = AppConfig.getInstance();
        // 保存API密钥
        for (Map.Entry<String, JTextField> entry : apiKeyFields.entrySet()) {
            String engineName = entry.getKey();
            String apiKey = entry.getValue().getText().trim();
            config.setApiKey(engineName, apiKey);
        }
        // 保存代理设置
        config.setProxyEnabled(enableProxyCheckBox.isSelected());
        config.setProxyHost(proxyHostField.getText().trim().isEmpty() ? "127.0.0.1" : proxyHostField.getText().trim());
        try {
            int port = Integer.parseInt(proxyPortField.getText().trim());
            config.setProxyPort(port);
        } catch (NumberFormatException e) {
            config.setProxyPort(7890);
        }
        config.setProxyUsername(proxyUsernameField.getText().trim());
        config.setProxyPassword(new String(proxyPasswordField.getPassword()));
        config.saveConfig();
    }
    
    /**
     * 检查配置是否已更改
     * 
     * @return 如果配置已更改返回true，否则返回false
     */
    public boolean isConfigChanged() {
        return configChanged;
    }
}